package gu.sql2java.observer;

import gu.simplemq.ISubscriber;
import gu.sql2java.SimpleLog;
import gu.sql2java.TableManager;
import gu.sql2java.manager.Managers;

import static com.google.common.base.Preconditions.checkArgument;

import com.google.common.base.Strings;

/**
 * 依赖 com.gitee.l0km:sql2java-manager
 * @author guyadong
 *
 */
public class RowObservers {
	/**
	 * 基于{@link TableManager}绑定{@code tables}指定的生成了sql2java表操作代码的表到{@link RowObserver}
	 * @param observer
	 * @param dbhostname 
	 * 数据库主机名，当有多个数据库主机连接同一个消息系统时用于在消息频道名中区分不同的数据库主机,可为空
	 * @param tables 表名
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static void bindSql2javaTables(RowObserver observer, String dbhostname, String ...tables){
		checkArgument(null != observer,"observer is null");
		if(null != tables){
			for(String tablename:tables){
				if(!Strings.isNullOrEmpty(tablename)){					
					TableManager m = Managers.getBaseTableManager(tablename);
					String schema = JDBCUtility.parseSchemaFromJDBCURL(m.getDataSourceConfig().getJdbcUrl());
					String qualifiedName = schema + "." + tablename;
					if(null != dbhostname){
						qualifiedName = dbhostname + "/" + qualifiedName;
					}
					SimpleLog.log("row observer register table {}  ",qualifiedName);
					observer.register(qualifiedName, m.getListenerContainer());
				}
			}
		}
	}
	/**
	 * 基于{@link TableManager}绑定{@code tables}指定的生成了sql2java表操作代码的表到{@link RowObserver}
	 * @param subscriber
	 * @param dbhostname 
	 * 数据库主机名，当有多个数据库主机连接同一个消息系统时用于在消息频道名中区分不同的数据库主机,可为空
	 * @param tables 表名
	 * @return {@link RowObserver}实例
	 */
	public static RowObserver bindSql2javaTables(ISubscriber subscriber, String dbhostname, String ...tables){
		RowObserver observer = new RowObserver(subscriber);
		bindSql2javaTables(observer, dbhostname, tables);
		return observer;
	}
}
